#ifndef DHD_REFCOUNT_H
#define DHD_REFCOUNT_H

#include <boost/intrusive_ptr.hpp>

namespace dhd
{
   class Refcounted
   {
      int refcount;
      
      friend void intrusive_ptr_add_ref( Refcounted * );
      friend void intrusive_ptr_release( Refcounted * );
      
    protected:
      virtual void on_zero_refcount() = 0;
      
    public:
      Refcounted() : refcount(0) {}
      
      virtual ~Refcounted(){}
   };
   
   
   // ----------------------------------------------------
   // Internal Referencecount Management Functions. 
   //             DO NOT CALL THESE
   // ----------------------------------------------------
   // 
#ifdef NO_USE_GCC_BUILTINS
   void intrusive_ptr_add_ref( Refcounted * r );
   void intrusive_ptr_release( Refcounted * r );
#else
   inline void intrusive_ptr_add_ref( Refcounted * r )
   {
       __sync_add_and_fetch( &r->refcount, 1 );
   }
   
   inline void intrusive_ptr_release( Refcounted * r )
   {
       if ( __sync_sub_and_fetch( &r->refcount, 1 ) == 0 )
           r->on_zero_refcount();
   }
#endif
   
}// end namespace dhd

#endif

